package cn.yogehaoren.topic;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author WangNing
 * @since 1.0
 */
public class TopicConsumer {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1. 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("k8s-node2");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        // 设置自动重连
        connectionFactory.setAutomaticRecoveryEnabled(true);
        connectionFactory.setNetworkRecoveryInterval(3000);

        //2. 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 3. 通过Connection创建Channel
        Channel channel = connection.createChannel();

        // 4. 声明
        String exchangeName = "test_topic_exchange";
        String queueName = "test_topic_queue_*";
        String routingKey = "user.*";
        // 声明交换机
        channel.exchangeDeclare(exchangeName, "topic", true, false, false, null);
        // 声明queue
        channel.queueDeclare(queueName, false, false, false, null);
        // 绑定 Exchange
        channel.queueBind(queueName, exchangeName, routingKey);

        // 5. 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        // 6. 设置channel
        channel.basicConsume(queueName, true, queueingConsumer);

        int count = 0 ;

        // 7. 获取消息
        while (true){

            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("消费端: "+msg);
            count ++;
            System.out.println(count);
        }


    }
}
